package com.ruoyi.finance.protal.shandpay.cashier.sdk;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @ClassName : HttpClient
 * @Description :http 表单请求工具类
 * @Author : Wcl
 * @DateTime : 2023/7/2 20:42
 * @Since JDK1.8.0_251
 **/
public class HttpClient {

    private static final Logger logger = LoggerFactory.getLogger(HttpClient.class);

    public static String doPost(String url, Map<String, String> params, int connectTimeout, int readTimeout) {
        try {
            logger.info("最终请求地址："+url);
            // 创建URL对象
            URL requestUrl = new URL(url);

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();

            // 设置连接超时时间
            connection.setConnectTimeout(connectTimeout);
            // 设置读取超时时间
            connection.setReadTimeout(readTimeout);

            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setDoOutput(true);

            // 构建请求参数
            StringBuilder paramBuilder = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                if (value != null && !value.isEmpty()) {
                    paramBuilder.append(key).append("=").append(URLEncoder.encode(value, "UTF-8")).append("&");
                } else {
                    paramBuilder.append(key).append("=").append("&");
                }
            }
            String requestBody = paramBuilder.toString();
            requestBody = requestBody.substring(0, requestBody.length() - 1);

            // 发送请求
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(requestBody.getBytes("UTF-8"));
            outputStream.flush();
            outputStream.close();

            // 获取响应状态码
            int responseCode = connection.getResponseCode();

            // 读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            if (responseCode == 200) {
                // 返回响应结果
                return response.toString();
            } else {
                logger.error("请求出错");
                return "请求出错";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "请求出错: " + e.getMessage();
        }
    }
}

